package org.sgx.gapitest.client.test;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.sgx.gapi.client.GAPI;
import org.sgx.gapi.client.apis.books.BooksModule;
import org.sgx.gapi.client.apis.youtube.Search;
import org.sgx.gapi.client.apis.youtube.SearchRequest;
import org.sgx.gapi.client.apis.youtube.SearchResponse;
import org.sgx.gapi.client.auth.AuthResponse;
import org.sgx.gapi.client.client.GAPICallback;
import org.sgx.gapi.client.loader.GAPILoader;
import org.sgx.gapi.client.loader.GAPILoaderCallback;
import org.sgx.gapi.client.loader.ModuleDefinition;
import org.sgx.gapi.client.util.GAPILoadCallback;
import org.sgx.gapitest.client.AbstractTest;
import org.sgx.gapitest.client.GAPITestConstants;
import org.sgx.gapitest.client.GAPITestTextResource;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * 
 * show how to use the youtube search API. No auth required. 
 * 
 * @author sg
 * 
 */
public class Youtube1 extends AbstractTest implements EntryPoint {

	@Override
	public void test(Element parent) {
		GAPI.load(new GAPILoadCallback() {
			@Override
			public void loaded() {
				main();
			}
		});
	}
	
	protected void main() {
		GAPI.get().client().setApiKey(GAPITestConstants.API_KEY);		
		ModuleDefinition moduleDef = new BooksModule(); 
		GAPILoader loader = new GAPILoader(moduleDef); 
		loader.load(new GAPILoaderCallback() {			
			@Override
			public void loaded(AuthResponse authResp) {
				callApi();
			}
		}); 
	}

	protected void callApi() {
		SearchRequest req = new SearchRequest();
		req.setPart("id,snippet"); 
		req.setQ("zaratustra"); 
		req.setType("video"); 
		req.execute(new GAPICallback<SearchResponse>() {
			@Override
			public void call(SearchResponse result) {
				if(result.error()!=null) {
					Window.alert("Error on Youtube Search request: "+result.error().message()); 
				}
				else {
					Collection<Search> items = result.itemsCol();
					String titles = ""; 
					for(Search s : items) 
						titles+=s.snippet().title()+", "; 
					Window.alert("Youtube Search response first "+items.size()+" titles : "+titles);
				}
			}
		}); 		
	}
	
	@Override
	public String getId() {
		return "youtube1";
	}
	
	@Override
	public String getDescription() {
		return "show how to use the youtube search API. No auth required.";
	}

	@Override
	public Map<String, GAPITestTextResource> getResources() {
		HashMap<String, GAPITestTextResource> m = new HashMap<String, GAPITestTextResource>();
		m.put("Youtube1.java", new GAPITestTextResource(TestResources.INSTANCE.Youtube1()));
		return m;
	}

	@Override
	public String[] getTags() {
		return null;
	}
	
	@Override
	public void onModuleLoad() {		
		test(RootPanel.getBodyElement()); 
	}

	
	
}
